import React, { useEffect, useState } from "react";
import style from "./style.less"
import ReactMarkdown from "react-markdown";
import gfm from 'remark-gfm'
import hljs from 'highlight.js'
import rehypeRaw from "rehype-raw";
import 'highlight.js/styles/foundation.css'
import { ITab } from "../../interface/tab";
import { getAllTab } from "../../service/tab";
import { IAddArticleParam } from "../../interface/Article";
import { getUserInfo } from "../../service/account";
import { publishArticle } from "../../service/article";
import { useNavigate } from "react-router-dom";
import { Modal } from "antd";
import LoginBox from "../LoginBox";
import cookieStore from "../../store/cookie";

export default function Create() {
  const [preView, setPreView] = useState<boolean>(false)
  const [inputText, setInputText] = useState<string>(``)
  const [title, setTitle] = useState<string>('')
  const [selectFile, setSelectFile] = useState<File>()
  const [img, setImg] = useState<File>()
  const [imgSrcs, setImgSrcs] = useState<string[]>([])
  const [showTabs, setShowTabs] = useState<boolean>(false)
  const [selectTabs, setSelectTabs] = useState<ITab[]>([])
  const [tabs, setTabs] = useState<ITab[]>([])
  const [showLoginModal, setShowLoginModal] = useState<boolean>(false)
  const [media, setMedia] = useState<'PC' | 'PHONE'>()
  const navigate = useNavigate()

  window.onresize = function () {
    const width = window.screen.availWidth
    if (width > 767) {
      setMedia('PC')
    } else {
      setMedia('PHONE')
    }
  }

  useEffect(() => {
    const width = window.screen.availWidth
    if (width > 767) {
      setMedia('PC')
    } else {
      setMedia('PHONE')
    }
    getTabs()
  }, [])

  async function getTabs() {
    const data = await getAllTab()
    if (data.stat === 'ok') {
      setTabs(data.data)
    } else {
      alert("数据错误，请刷新页面")
    }
  }

  useEffect(() => {
    // 配置 highlight.js
    hljs.configure({
      // 忽略未经转义的 HTML 字符
      ignoreUnescapedHTML: true
    })
    // 获取到内容中所有的code标签
    const codes = document.querySelectorAll('code')
    codes.forEach((el) => {
      // 让code进行高亮
      hljs.highlightElement(el as HTMLElement)
    })
  }, [inputText])

  useEffect(() => {
    if (img !== undefined) {
      const read = new FileReader()
      read.readAsDataURL(img as Blob)
      read.onload = (e) => {
        const inputArea = document.getElementById('contentInput') as HTMLTextAreaElement
        const content: string = e.target?.result as string
        setImgSrcs([...imgSrcs, content])
        const [startPos, endPos] = [inputArea?.selectionStart, inputArea.selectionEnd]
        const insertTxt = `<br /><img id="url${imgSrcs.length}" /><br />`
        if (startPos === undefined || endPos === undefined) return;
        const txt = inputArea?.value;
        const result = txt.substring(0, startPos) + insertTxt + txt.substring(endPos);
        setInputText(result);
      }
    }
    // eslint-disable-next-line
  }, [img])

  useEffect(() => {
    if (selectFile !== undefined) {
      const read = new FileReader()
      setTitle(selectFile.name.trim().slice(0, -3))
      read.readAsText(selectFile as Blob, 'UTF-8')
      read.onload = (e) => {
        const content: string = e.target?.result as string
        setInputText(content)
      }
    }
  }, [selectFile])

  useEffect(() => {
    if (title.length > 50) {
      setTitle(title.slice(0, 50))
    }
  }, [title])

  function showSrc(text: string) {
    var result = text.replace(/<img [^>]*id=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
      const index = capture.slice(3)
      return `<img src='${imgSrcs[Number(index)]}' style="max-height:90px;max-width:100%;height:auto;display:block;margin:10px 0;"/>`;
    });
    return result
  }

  function addTab(tab: ITab) {
    if (selectTabs.length < 5) {
      setSelectTabs([...selectTabs, tab])
      setTabs(tabs.filter((item: ITab) => item.value !== tab.value))
    } else {
      alert('标签数量已达上限')
    }
  }

  function delTab(tab: ITab) {
    setTabs([...tabs, tab])
    setSelectTabs(selectTabs.filter((item: ITab) => item.value !== tab.value))
  }

  async function handlePublish() {
    const data = await getUserInfo({ account: sessionStorage.getItem("stageUser")! }, cookieStore.getState().toString())
    if (data.stat === "ok") {
      publishHandle(
        {
          title: title,
          content: showSrc(inputText),
          tabs: selectTabs,
          author: data.data.id,
          like: [],
          save: []
        })
    } else {
      alert("请先登录")
      setShowLoginModal(true)
    }
  }

  async function reFreshUserAfterLogin() {
    setShowLoginModal(false)
    const data = await getUserInfo({ account: sessionStorage.getItem("stageUser")! }, cookieStore.getState().toString())
    if (data.stat === "ok") {
      // publishHandle()
    } else {
      alert("请先登录")
      setShowLoginModal(true)
    }
  }

  async function publishHandle(params: IAddArticleParam) {
    const data = await publishArticle(params)
    const titleBool: boolean = (title.length <= 50 && title.length >= 3)
    const contentBool: boolean = (inputText.length > 0)
    const tabBool: boolean = (selectTabs.length <= 5 && selectTabs.length > 0)
    if (!(titleBool && contentBool && tabBool)) {
      alert("参数缺失或不符合规定")
      return
    }
    if (data.stat === 'ok') {
      alert("发布成功，确认后返回首页")
      navigate("/home")
      window.location.reload()
    } else {
      alert(data.msg)
    }
  }

  return (
    <React.Fragment>
      <div>
        <div className={style.createContent}>
          <div className={style.toolBar}>
            <div><span className={style.fileBtn}>上传md文件</span><input onChange={(value) => { setSelectFile(value.target.files![0]) }} type={"file"} accept={'.md'} className={style.fileInput} /></div>
            <div><span className={style.onPreView}>插入图片</span><input onChange={(value) => { setImg(value.target.files![0]) }} type={"file"} accept={'image/*'} className={style.imgInput} /></div>
            {media === 'PC' && (<div><span className={preView ? style.onPreView : style.unPreView} onClick={() => { setPreView(!preView) }}>{preView ? "关闭预览" : "开启预览"}</span></div>)}
            <div><span onClick={() => { setInputText(''); setTitle('') }} className={style.onPreView}>清除内容</span></div>
            <div><span className={style.onPreView} onClick={() => { showTabs ? setSelectTabs([]) : setShowTabs(!showTabs) }}>{showTabs ? "清空选择" : "查看并选择选择文章标签(至少一个)"}</span></div>
            <div>{showTabs ? (<span className={style.onPreView} onClick={() => { setShowTabs(!showTabs) }}>确认选择以下标签</span>) : <span></span>}</div>
            <div><span onClick={() => { handlePublish() }} className={style.onPreView}>发布</span></div>
          </div>
          {showTabs ? (
            <div className={style.tabChoose}>
              <div className={style.openGuideBar}>
                {tabs.map((block: ITab, index: number) => {
                  return (
                    <div onClick={() => { addTab(block) }} className={style.block} key={index + block.value} >
                      <span>{block.lable}</span>
                    </div>
                  )
                })}
              </div>
              <div className={style.selectTabs}>
                <p>请选择标签，至少一个，最多五个</p>
                {selectTabs.map((tab: ITab, index: number) => {
                  return (
                    <div onClick={() => { delTab(tab) }} className={style.selectTab} key={index + tab.value}>
                      <span>{tab.lable}</span>
                    </div>
                  )
                })}
              </div>
            </div>) : (<div></div>)}
          <div>
            <div className={style.titleBar}><span className={style.biaoti}>标题:</span><input type={'text'} placeholder={"输入您想要发表文章的标题，不要超过50字,不少于三个字"} className={style.titleInput} value={title} onChange={(value) => { setTitle(value.target.value.trim()) }} /><span onClick={() => { setTitle('') }} className={style.clearText}>清除标题</span></div>
            <div className={preView ? style.editShow : style.edit}>
              <div><span>{`编辑区 字数：${inputText.length}`}</span><textarea placeholder="上限5000字" id={'contentInput'} value={inputText} onChange={(value) => {
                setInputText(value.target.value);
              }} className={style.inputArea} /></div>
              {preView ? (<div className={style.markdownShow}><span>预览区</span><ReactMarkdown remarkPlugins={[gfm]} rehypePlugins={[rehypeRaw]} children={showSrc(inputText)} /></div>) : (<div></div>)}
            </div>
          </div>
        </div>
        <Modal destroyOnClose onCancel={() => { setShowLoginModal(false) }} footer={null} className={style.interrap} visible={showLoginModal}>
          <LoginBox afterLogin={() => { reFreshUserAfterLogin() }} />
        </Modal>
      </div>
    </React.Fragment>
  )
}